//二叉树的最近公共祖先
class Solution {
private:
    TreeNode* ans = nullptr;
public:
    bool dfs(TreeNode* root,TreeNode* p,TreeNode* q)
    {
        if(root == nullptr){
            return false;
        }
        bool l = dfs(root->left,p,q);
        if(ans){  //剪枝
            return true;
        }
        bool r = dfs(root->right,p,q);
        if((l && r) || ((root->val == p->val || root->val == q->val) && (l || r))){
            ans = root;
        }
        return (root->val == p->val) || (root->val == q->val) || (l || r);
    }
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        dfs(root,p,q);
        return ans;
    }